import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnChanges,
  AfterViewChecked
} from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'time-option',
  templateUrl: './time-option.html',
  styleUrls: ['time-option.scss']
})
export class TimeOptionComponent implements OnChanges, AfterViewChecked {
  datepipe;
  datenow;
  upperDate;
  datenowStr;

  canAdd = false;
  timeType = 0;

  @Input() state;
  @Input() titles;

  @Output() timeTypeChange: EventEmitter<any> = new EventEmitter();

  constructor() {
    this.datepipe = new DatePipe('en-US');
    this.datenow = new Date();
    this.upperDate = this.datenow;
    this.datenowStr = this.datepipe.transform(this.datenow, 'yyyy/MM/dd');
  }

  ngOnChanges(changes) {
    if (changes.state.currentValue.reset === true) {
      this.timeType = 0;
      this.datenow = new Date();
      this.datenowStr = this.datepipe.transform(this.datenow, 'yyyy/MM/dd');
      this.canAdd = false;
    }
  }

  ngAfterViewChecked() {
    if (this.state.reset === true) {
      this.timeType = 0;
      this.datenow = new Date();
      this.datenowStr = this.datepipe.transform(this.datenow, 'yyyy/MM/dd');
      this.canAdd = false;
    }
  }


  setType(i) {
    this.state.reset = false;
    this.timeType = i;
    this.canAdd = this.isNotOverUpperDate(i, this.datenow, this.upperDate);
    this.timeTypeChange.emit({
      time: this.datenowStr,
      timeType: this.timeType,
    });
  }

  setTime(increment) {
    this.state.reset = false;
    this.datenow = this.getTimeAfterIncre(
      this.timeType,
      this.datenow,
      increment
    );
    this.datenowStr = this.datepipe.transform(this.datenow, 'yyyy/MM/dd');
    this.canAdd = this.isNotOverUpperDate(
      this.timeType,
      this.datenow,
      this.upperDate
    );
    this.timeTypeChange.emit({
      time: this.datenowStr,
      timeType: this.timeType,
    });
  }

  getTimeAfterIncre(way, time, increment) {
    switch (way) {
      case 0:
        time.setDate(time.getDate() + increment);
        break;
      case 1:
        time.setMonth(time.getMonth() + increment);
        break;
      case 2:
        time.setFullYear(time.getFullYear() + increment);
        break;
      case 3:
        if (increment === 1) {
          time.setDate(time.getDate() + 7);
        } else {
          time.setDate(time.getDate() - 7);
        }
    }
    return time;
  }

  isNotOverUpperDate(way, timenow, upperDate) {
    timenow = this.getTimeAfterIncre(way, new Date(timenow.valueOf()), 1);
    return (
      this.datepipe.transform(upperDate, 'yyyy-MM-dd') >=
      this.datepipe.transform(timenow, 'yyyy-MM-dd')
    );
  }
}
